<?php

namespace App\Http\Resources;

use App\Traits\BaseResource;
use Illuminate\Http\Resources\Json\Resource;

class User extends Resource {
	use BaseResource;

	public function toEdit($request) {
		return $this->filterFields([
			'id' => $this->id,
			'avatar' => $this->avatar,
			'name' => $this->name,
			'nick_name' => $this->nick_name,
			'email' => $this->email,
			'status' => $this->status,
			'is_admin' => $this->is_admin,
			'website' => $this->website,
			'description' => $this->description,
			'email_notify_enabled' => $this->email_notify_enabled,
		]);
	}

	public function toIndex($request) {
		return $this->filterFields([
			'id' => $this->id,
			'avatar' => $this->avatar,
			'name' => $this->name,
			'nick_name' => $this->nick_name,
			'website' => $this->website,
			'description' => $this->description,
			'email_notify_enabled' => $this->email_notify_enabled,
			'comment' => $this->whenLoaded('comments', function () {
				return (new CommentCollection($this->comments->load(['item', 'user', 'reply'])))->type('user');
			}),
			'message' => $this->whenLoaded('messages', function () {
				return (new MessageCollection($this->messages->load(['user', 'reply'])))->type('user');
			}),
		]);
	}

	public function toInfo($request) {
		return [
			'avatar' => $this->avatar,
			'name' => $this->name,
			'email' => $this->email,
			'hash' => (boolean) $this->is_admin,
			'nick_name' => $this->nick_name,
			'website' => $this->website,
			'description' => $this->description,
			'weibo' => $this->weibo,
			'github' => $this->github,
			'email_notify_enabled' => $this->email_notify_enabled,
			'created_at' => $this->created_at,
			'updated_at' => \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $this->updated_at)->diffForHumans(),
		];
	}

	public function toDefault($request) {
		return $this->filterFields([
			'id' => $this->id,
			'avatar' => $this->avatar,
			'name' => $this->name,
			'email' => $this->email,
			'comments_nums' => $this->whenLoaded('comments', function () {
				return $this->comments->count();
			}),
			'approves_nums' => $this->whenLoaded('approves', function () {
				return $this->approves->count();
			}),
			'status' => $this->status,
			'is_admin' => $this->is_admin,
			'created_at' => $this->created_at,
			'updated_at' => $this->updated_at,
		]);
	}
}
